﻿using System.Collections.Generic;
using System.Windows;
using Game.Common;

namespace Game.Map.Internal
{
    class AdjacentFields : IEnumerable<IMapField>
    {
        readonly List<IMapField> _Fields = new List<IMapField>();
        readonly Dictionary<ObjectOrientation, IMapField> _Dictionary;
        readonly IGameMap _GameMap;
        readonly Point _Start;
        
        public AdjacentFields(
            IGameMap map, 
            Point start, 
            bool includeCenter = false)
        {
            _GameMap = map;
            _Start = start;
            _Dictionary = new Dictionary<ObjectOrientation, IMapField>();
            
            Add(0, -1, ObjectOrientation.North);
            if (includeCenter)
            {
                Add(0, 0, ObjectOrientation.Center);
            }
            Add(0, 1, ObjectOrientation.South);
            
            if ((start.X % 2) == 0)
            {
                Add(-1, 0, ObjectOrientation.Northwest);
                Add(1, 0, ObjectOrientation.Northeast);
            
                Add(-1, 1, ObjectOrientation.Southwest);
                Add(1, 1, ObjectOrientation.Southeast);
            }
            else
            {
                Add(-1, -1, ObjectOrientation.Northwest);
                Add(1, -1, ObjectOrientation.Northeast);
                
                Add(-1, 0, ObjectOrientation.Southwest);
                Add(1, 0, ObjectOrientation.Southeast);
            }
        }

        void Add(double dx, double dy, ObjectOrientation orientation)
        {
            double x = _Start.X + dx;
            double y = _Start.Y + dy;
            Point point = new Point(x, y);
            if (_GameMap.Fields.Contains(point)) 
            {
                _Fields.Add(_GameMap.Fields[point]);
                _Dictionary.Add(orientation, _GameMap.Fields[point]);
            }
        }
        
        public IMapField this[ObjectOrientation orientation]
        {
            get 
            {
                if (!_Dictionary.ContainsKey(orientation))
                {
                    return null;
                }
                
                return _Dictionary[orientation];
            }
        }
        
        public IEnumerator<IMapField> GetEnumerator()
        {
            return _Fields.GetEnumerator();
        }
        
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _Fields.GetEnumerator();
        }
    }
}
